var express = require('express');
var router = express.Router();
let multiparty = require('multiparty')
const nodemailer = require('nodemailer');
let jwt = require('jsonwebtoken')
let { StudenModel, CateModel, loginModel,ListModel } = require('../model/model')
const transporter = nodemailer.createTransport({
  host: "smtp.qq.com",				// QQ邮箱的SMTP地址
  port: 465,									// 每个邮箱的端口号可能是一样的，一般都使用
  secure: true,               // 使用SSL加密
  auth: {
    "user": '3269316552@qq.com', 		// 你自己的邮箱的邮箱地址
    "pass": 'eytsmeskgdojcjge'         // 上面我们提到的授权码
  }
});
// 生成验证码
function getCode() {
  let str = "";
  for (let i = 0; i < 6; i++) {
    str += parseInt(Math.random() * 10)
  }
  return str;
}

let sendMails = (mail, code) => {
  // 邮件信息
  let mailObj = {
    from: '3269316552@qq.com',                  // 发送方邮箱
    to: mail,                                   // 接收方邮箱
    subject: '口袋钱包测试邮件',                  //主题
    text: `您的验证码是${code},有效时间五分钟`     // 内容
  }
  //  发送验证码
  transporter.sendMail(mailObj, (err, data) => {
    console.log(err);
    console.log(data);
  })
}
router.post('/show', async (req, res) => {
  let { user } = req.body
  //  生成验证码
  let code = getCode();
  console.log(code, user);

  sendMails(user, code)
  res.send({
    code: 200
  })
})
router.post('/addTab', async (req, res) => {
  await loginModel.create(req.body)
  res.send({
    code: 200,
    msg: '添加成功'
  })
})
router.post('/updTab', async (req, res) => {
  await loginModel.updateOne({ _id: req.body.id }, req.body)
  res.send({
    code: 200,
    msg: '修改成功'
  })
})
router.get('/list', async (red, res) => {
  let { search } = red.query
  console.log(search);

  let data = await CateModel.find({ name: { $regex: search } })
  res.send({
    code: 200,
    data
  })
})
router.get('/list123123123', async (red, res) => {
  let { search } = red.query
  console.log(search);

  let data = await CateModel.find({ name: { $regex: search } })
  res.send({
    code: 200,
    data
  })
})

// list添加数据
router.post('/addList',async(req,res)=>{
  await ListModel.create(req.body)
  res.send({
    code:200,
    msg:'添加成功'
  })
})
// list获取数据
router.get('/getList',async(req,res)=>{
  let data = await ListModel.find()
  res.send({
    code:200,
    data:data
  })
})
module.exports = router;
